package com.youzikj.wx.core.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.youzikj.wx.comm.oauth2.SNSUserInfo;
import com.youzikj.wx.comm.util.CommonUtil;
import com.youzikj.wx.core.comm.Utils;
import com.youzikj.wx.core.pojo.Pub;
import com.youzikj.wx.core.pojo.Sub;
import com.youzikj.wx.core.pojo.Task;
import com.youzikj.wx.core.pojo.User;
import com.youzikj.wx.core.service.CoreService;
import com.youzikj.wx.core.service.PubServiceImpl;
import com.youzikj.wx.core.service.SubServiceImpl;
import com.youzikj.wx.core.service.UserServiceImpl;
import com.youzikj.wx.core.utils.BDyunUtil;
import com.youzikj.wx.core.utils.FileUtil;
import com.youzikj.wx.core.utils.PosterUtil;
import com.youzikj.wx.pay.JsConfig;

@RestController
@RequestMapping(value = "/wycd/")
public class TaskController {

	private static final Logger log = Logger.getLogger(TaskController.class);

	@Autowired
	private CoreService service;
	
	@Autowired
	private UserServiceImpl userService;
	
	@Autowired
	private SubServiceImpl subService;
	
	@Autowired
	private PubServiceImpl pubService;
	

	// 入口
	@RequestMapping(value = "menu")
	public ModelAndView menu(HttpServletRequest request,HttpServletResponse resp) {
		log.info("你已点击菜单");
		String code = request.getParameter("code");
		log.info("=========code:" + code);
		if (code == null) {
			try {
				resp.sendRedirect("http://open.weixin.qq.com/connect/oauth2/authorize?appid=wxca78deeb014de180&redirect_uri=http%3a%2f%2fwycd.youzikj.com%2fwycd%2fmenu&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		SNSUserInfo userInfo = Utils.getUserInfoByCode(code);
		Pub pub = new Pub();
		pub.setHead_url(userInfo.getHeadImgUrl());
		pub.setNickname(userInfo.getNickname());
		pub.setOpenid(userInfo.getOpenId());
		try {
			pubService.addPub(pub);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Sub sub = new Sub();
		sub.setHead_url(userInfo.getHeadImgUrl());
		sub.setNickname(userInfo.getNickname());
		sub.setOpenid(userInfo.getOpenId());
		try {
			subService.addSub(sub);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		ModelAndView model = new ModelAndView();
		model.addObject("openid", userInfo.getOpenId());
		model.setViewName("index");
		return model;
	}

//	@RequestMapping(value = "index")
//	public ModelAndView index(HttpServletRequest request,
//			HttpServletResponse resp) {
//		String code = request.getParameter("code");
//		if (code == null) {
//			try {
//				resp.sendRedirect("http://open.weixin.qq.com/connect/oauth2/authorize?appid=wxca78deeb014de180&redirect_uri=http%3a%2f%2fwycd.youzikj.com%2fwycd%2findex&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}
//		SNSUserInfo userInfo = Utils.getUserInfoByCode(code);
//		ModelAndView model = new ModelAndView();
//		model.addObject("openid", userInfo.getOpenId());
//		model.setViewName("index");
//		return model;
//	}
	
	@RequestMapping(value = "releaseTask")
	public ModelAndView releaseTask(HttpServletRequest request) {
		String openid = request.getParameter("openid");
		ModelAndView model = new ModelAndView();
		// 页面获取js权限
		String jsapiTicket = CommonUtil.getJsapiTicket(CommonUtil.getToken(
				CommonUtil.appId, CommonUtil.appSecret).getAccessToken());
		JsConfig jsConfig = JsConfig.sign(jsapiTicket,"http://wycd.youzikj.com/wycd/releaseTask");
		
		model.addObject("jsConfig", jsConfig);
		model.addObject("openid", openid);
		model.setViewName("weuiTask");
		return model;
	}

	/**
	 * 发布任务
	 * 
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "save")
	public ModelAndView save(HttpServletResponse response,
			HttpServletRequest request) {
		ModelAndView model = new ModelAndView();
		String openid = request.getParameter("openid");
		String title = request.getParameter("title");
		String link = request.getParameter("link");
		String start_date = request.getParameter("start_date");
		String end_date = request.getParameter("end_date");
		String amount = request.getParameter("amount");
		String current_num = request.getParameter("current_num");
		Pub pub = new Pub();
		pub.setOpenid(openid);
		Task t = new Task();
		t.setTitle(title);
		t.setLink(link);
		t.setStart_date(start_date);
		t.setEnd_date(end_date);
		t.setAmount(Integer.parseInt(amount));
		t.setCurrent_num(Integer.parseInt(current_num));
		t.setPub(pub);
		t.setImage_url("http://wycd-yzkj.gz.bcebos.com/poster/0_0000s_0005_108.png");
		try {
			service.pubTask(t);
			log.info("保存任务成功");
		} catch (Exception e) {
			log.info("保存任务失败");
		}
		model.setViewName("panel");
		List<Task> list = service.all();
		model.addObject("list", list);
		model.addObject("openid", openid);
		return model;
	}

	
	//点击确定  领取任务 生成二维码
		@RequestMapping(value="receive")
		public  ModelAndView receive(HttpServletRequest request){
			ModelAndView model = new ModelAndView();
			String taskId = request.getParameter("taskId");
			System.out.println("点击确定taskId:"+taskId);
			String openid = request.getParameter("openid");
			System.out.println("点击确定openid:"+openid);
			Sub sub = subService.queryByOpenid(openid);
			String state = taskId+"_"+sub.getId();
			String posterUrl = null;
			try{
				String smallPath = FileUtil.getQrcode(request, state);
				 String path = request.getSession().getServletContext().getRealPath(File.separator);
				 path += "upload" + File.separator;
				 String bigPath = path +"big.jpg";
				String posterImage = PosterUtil.overlapImage(request, taskId, bigPath, smallPath);
				String name ="poster"+state +".jpg";
				BDyunUtil.upload(name, posterImage);
				posterUrl= BDyunUtil.generatePresignedUrl(name);
				System.out.println("海报地址:"+posterUrl);
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				subService.editPosterUrl(sub);
			} catch (Exception e) {
				log.info("保存海报地址失败");
			}
			Task task = null;
			try {
				service.subTask(Integer.parseInt(taskId), openid, posterUrl);
				//查询任务
				task = service.getBySubId(Integer.parseInt(taskId), sub.getId());
			} catch (Exception e) {
				log.info("领取任务失败");
			}
			model.addObject("task",task);
			model.addObject("Sub",sub);
			model.setViewName("taskDetails");
			return model;
			
		}
		
		@RequestMapping(value ="getcode")
		public void getcode(HttpServletRequest request,HttpServletResponse resp){
			String code = request.getParameter("code");
			String state = request.getParameter("state");
			if(state != null && code != null){
				String[] split = state.split("_");
				String taskId = split[0];
				String subId = split[1];
				System.out.println("code:=="+code+"taskId:=="+taskId+"subId=="+subId);
				SNSUserInfo userInfo = Utils.getUserInfoByCode(code);
				User user = new User();
				user.setHead_url(userInfo.getHeadImgUrl());
				user.setNickname(userInfo.getNickname());
				user.setOpenid(userInfo.getOpenId());
				try {
					userService.addUser(user);
					service.qrCode(userInfo.getOpenId(), Integer.parseInt(taskId), Integer.parseInt(subId));
				} catch (Exception e) {
					log.info("添加扫码用户失败"+e);
				}
			}
			
			//查询宣传地址，重定向	
			try {
			    resp.sendRedirect("http://qymm02.joywii.net:9090/mjindex");
		    } catch (IOException e) {
			log.error("重定向失败", e);
		}
			
		}	
		
		//任务详情
		@RequestMapping(value="taskDetails")
		public ModelAndView taskDetails(HttpServletRequest request){
			ModelAndView model = new ModelAndView();
			String taskid = request.getParameter("taskId");
			String openid = request.getParameter("openid");
			String subid = request.getParameter("subId");
			log.info("任务详情taskid:"+taskid+"任务详情：openid:"+openid);
			Integer taskId = Integer.parseInt(taskid);
			Task task = null;
			if(subid != null){
				int subId = Integer.parseInt(subid);
			    task = service.getBySubId(taskId, subId);
			    List<User> userList = userService.query(taskId, subId);
			    model.addObject("userList", userList);
			} else{
				//未领取
				task = service.get(taskId);
			}
			model.addObject("task",task);
			model.addObject("openid",openid);
			model.setViewName("taskDetails");
			return model;
		}
		
}
